package com.zhanghe.study.netty.decoder.fixed;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import static io.netty.util.internal.ObjectUtil.checkPositive;

/**
 * @author zh
 * @date 2022/2/18 11:07
 */
public class FixedLengthFrameEncoder extends MessageToByteEncoder<String> {

    private final int frameLength;

    /**
     * Creates a new instance.
     *
     * @param frameLength the length of the frame
     */
    public FixedLengthFrameEncoder(int frameLength) {
        checkPositive(frameLength, "frameLength");
        this.frameLength = frameLength;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        if(msg.length() > frameLength){
            throw new RuntimeException("消息长度过长");
        }
        if(msg.length() < frameLength){ // 不足的使用空格补齐
            StringBuilder builder = new StringBuilder(msg);
            int difference = frameLength - msg.length();
            for (int i = 0; i < difference; i++) {
                builder.append(" ");
            }
            msg = builder.toString();
        }
        ctx.writeAndFlush(Unpooled.wrappedBuffer(msg.getBytes()));
    }
}
